<template>
  <div class="user-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="list-header">
          <h2>用户列表</h2>
          <div class="header-actions">
            <el-button
                type="primary"
                @click="handleAddUser"
                size="small"
                class="add-btn"
            >
              <el-icon><Plus /></el-icon>
              <span>新增用户</span>
            </el-button>
            <el-button
                type="info"
                @click="$emit('closeUserList')"
                size="small"
                class="close-btn"
            >
              <el-icon><Close /></el-icon>
              <span>关闭</span>
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索表单 -->
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="用户名">
          <el-input
              v-model="searchForm.name"
              placeholder="请输入用户名"
              clearable
              style="width: 180px"
          />
        </el-form-item>
        <el-form-item label="状态">
          <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
          >
            <el-option label="启用" value="0" />
            <el-option label="禁用" value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 用户表格 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="name" label="用户名" width="120" align="center"/>
        <el-table-column prop="phone" label="手机号" width="240" align="center"/>
        <el-table-column prop="email" label="邮箱" width="240" align="center"/>
        <el-table-column prop="roles" label="角色" width="240" align="center">
          <template #default="{ row }">
            <el-tag :type="row.roles.includes('ADMIN') ? 'danger' : 'info'">
              {{ row.roles.includes('ADMIN') ? '管理员' : '普通用户' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="deleted" label="状态" width="240" align="center">
          <template #default="{ row }">
            <el-tag :type="row.deleted === 0 ? 'success' : 'warning'">
              {{ row.deleted === 0 ? '正常' : '已删除' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" align="center">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination-container">
        <el-pagination
            v-model:current-page="pagination.current"
            v-model:page-size="pagination.size"
            :page-sizes="[10, 20, 50, 100]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="pagination.total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑用户对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="50%"
    >
      <el-form ref="userFormRef" :model="userForm" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="name">
          <el-input v-model="userForm.name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio label="1">启用</el-radio>
            <el-radio label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="角色" prop="roles">
          <el-select v-model="userForm.roles" multiple placeholder="请选择角色">
            <el-option
                v-for="role in roleOptions"
                :key="role.value"
                :label="role.label"
                :value="role.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Close } from '@element-plus/icons-vue'
import api from '@/api'

// 搜索表单
const searchForm = reactive({
  name: '',
  status: ''
})

// 用户列表数据
const userList = ref([])

// 分页数据
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 获取用户列表
const fetchUserList = async () => {
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      username: searchForm.name || '',
      status: searchForm.status
    }
    console.log(params,"==========")
    const response = await api.user.list(params)

    if (response.code === 200) {
      userList.value = response.data
    } else {
      ElMessage.error(response.msg || '获取用户列表失败')
    }
  } catch (error) {
    console.error('获取用户列表出错:', error)
    ElMessage.error('获取用户列表失败，请检查网络')
  }
}

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('添加用户')
const userForm = reactive({
  id: '',
  name: '',
  nickname: '',
  email: '',
  phone: '',
  status: '1',
  roles: []
})
const userFormRef = ref(null) // 表单引用

// 角色选项
const roleOptions = [
  { value: 'admin', label: '管理员' },
  { value: 'editor', label: '编辑' },
  { value: 'viewer', label: '查看者' }
]

// 表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
})

// 搜索方法
const handleSearch = () => {
  pagination.current = 1 // 搜索时重置到第一页
  fetchUserList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.name = ''
  searchForm.status = ''
  handleSearch()
}

// 分页方法
const handleSizeChange = (val) => {
  pagination.size = val
  pagination.current = 1
  fetchUserList()
}

const handleCurrentChange = (val) => {
  pagination.current = val
  fetchUserList()
}

// 添加用户
const handleAddUser = () => {
  dialogTitle.value = '添加用户'
  userForm.id = ''
  userForm.name = ''
  userForm.nickname = ''
  userForm.email = ''
  userForm.phone = ''
  userForm.status = '1'
  userForm.roles = []
  // 打开对话框后聚焦到用户名输入框
  nextTick(() => {
    if (userFormRef.value) {
      userFormRef.value.findField('name')?.focus()
    }
  })
  dialogVisible.value = true
}

// 编辑用户
const handleEdit = (row) => {
  dialogTitle.value = '编辑用户'
  console.log(row,"=============")
  Object.assign(userForm, {
    id: row.id,
    name: row.name,
    email: row.email || '',
    phone: row.phone || '',
    status: row.status + '', // 转为字符串
    roles: row.roles || []
  })
  dialogVisible.value = true
}

// 删除用户
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除用户 "${row.name}" 吗?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 实际项目中应调用删除API
    ElMessage.success('删除成功')
    fetchUserList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const submitForm = () => {
  if (!userFormRef.value) return
  userFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        let response
        if (userForm.id) {
          // 编辑用户
          response = await api.user.update(userForm)
          ElMessage.success('更新用户成功')
        } else {
          // 新增用户
          response = await api.user.create(userForm)
          ElMessage.success('新增用户成功')
        }
        if (response.code === 200) {
          dialogVisible.value = false
          fetchUserList()
        } else {
          ElMessage.error(response.msg || '操作失败')
        }
      } catch (error) {
        console.error('提交表单出错:', error)
        ElMessage.error('操作失败，请重试')
      }
    } else {
      console.log('表单验证失败')
      return false
    }
  })
}

onMounted(() => {
  fetchUserList()
})
</script>

<style scoped>
.user-list-container {
  height: 80vh;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.box-card {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 10px;
}

.list-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.close-btn, .add-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 7px 12px;
  border-radius: 4px;
}

.close-btn .el-icon, .add-btn .el-icon {
  margin-right: 5px;
  font-size: 14px;
}

.search-form {
  margin-bottom: 15px;
}

.table-container {
  flex: auto;
  margin-bottom: 15px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  padding: 10px 0;
  background: #fff;
  border-top: 1px solid #ebeef5;
}

/* 深度样式调整 */
:deep(.el-table) {
  flex: 1;
}

:deep(.el-table .cell) {
  padding: 8px 0;
}

:deep(.el-pagination) {
  padding: 0;
}

:deep(.el-pagination.is-background .el-pager li:not(.is-disabled).is-active) {
  background-color: #409eff;
  color: white;
}

:deep(.el-pagination__jump) {
  margin-left: 10px;
}
</style>